package com.itfreer.data.check.imp;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.itfreer.data.check.ICheck;
import com.itfreer.utils.json.JsonUtils;

/**
 * 最大长度检查
 */
@Component("MaxlenCheck")
public class MaxlenCheck implements ICheck {
	/**
	 * 定义进行检查标准类
	 * 
	 * @param entity
	 *            object对象
	 * @param paraString
	 *            {field:"x.y"} 字段名:"长度.精度"
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String runCheck(Object entity, String paraString) {
		// 数据只支持Map对象，当前
		if (!(entity instanceof Map)) {
			return "只支持Map类型的检查数据格式";
		}
		Map<String, Object> data = (Map<String, Object>) entity;
		if (data == null || data.size() <= 0) {
			return null;
		}
		if (paraString == null || paraString.equals("")) {
			return null;
		}

		List<MaxlenCheckPara> paras = (List<MaxlenCheckPara>) JsonUtils.toBean(paraString,
				JsonUtils.getCollectionType(List.class, MaxlenCheckPara.class));
		if (paras == null || paras.size() <= 0) {
			return "检查参数转换失败";
		}

		for (MaxlenCheckPara para : paras) {
			if (!data.containsKey(para.getFieldName())) {
				return "配置的字段【" + para.getFieldAliasName() + "】在数据中不存在";
			}
			Object value = data.get(para.getFieldName());
			if (value == null || value.toString().equals("")) {
				continue;
			}

			String valueString = value.toString();
			String lenString = para.getFieldLen();

			String[] lenMsg = lenString.split(".");
			if (lenMsg.length == 1) {
				if (valueString.length() > Integer.parseInt(lenMsg[0])) {
					return "字段【" + para.getFieldAliasName() + "】值【" + value + "】长度超过" + lenMsg[0];
				}
			} else if (lenMsg.length == 2) {
				if (valueString.length() > Integer.parseInt(lenMsg[0])) {
					return "字段【" + para.getFieldAliasName() + "】值【" + value + "】长度超过" + lenMsg[0];
				}
				String[] valueMsg = valueString.split(".");
				if (valueMsg[valueMsg.length - 1].length() > Integer.parseInt(lenMsg[1])) {
					return "字段【" + para.getFieldAliasName() + "】值【" + value + "】精度超过" + lenMsg[1];
				}
			}
		}

		return null;
	}
}
